import { pathExists } from 'fs-extra';
import { join } from 'path';

import c from '../colors';
import { check } from '../common';
import type { Config } from '../definitions';
import { fatal, isFatal } from '../errors';
import { logSuccess } from '../log';

export async function doctorOhos(config: Config): Promise<void> {
  try {
    await check([() => checkOhosInstalled(config), () => checkOhosAppDirs(config)]);
    logSuccess('HarmonyOS looking great! 👌');
  } catch (e: any) {
    if (!isFatal(e)) {
      fatal(e.stack ?? e);
    }

    throw e;
  }
}

async function checkOhosInstalled(config: Config): Promise<string | null> {
  if (!(await pathExists(config.ohos.platformDirAbs))) {
    return `HarmonyOS platform directory ${c.strong(config.ohos.platformDir)} is missing`;
  }
  return null;
}

async function checkOhosAppDirs(config: Config): Promise<string | null> {
  if (!(await pathExists(config.ohos.entryDirAbs))) {
    return `${c.strong(config.ohos.entryDir)} directory is missing in ${c.strong(config.ohos.platformDir)}`;
  }

  if (!(await pathExists(config.ohos.srcDirAbs))) {
    return `${c.strong(config.ohos.srcDir)} directory is missing in ${c.strong(config.ohos.platformDir)}`;
  }

  if (!(await pathExists(config.ohos.assetsDirAbs))) {
    return `${c.strong(config.ohos.assetsDir)} directory is missing in ${c.strong(config.ohos.platformDir)}`;
  }

  if (!(await pathExists(config.ohos.webDirAbs))) {
    return `${c.strong(config.ohos.webDir)} directory is missing in ${c.strong(config.ohos.platformDir)}`;
  }

  const indexHtmlPath = join(config.ohos.webDirAbs, 'index.html');
  if (!(await pathExists(indexHtmlPath))) {
    return `${c.strong('index.html')} file is missing in ${c.strong(config.ohos.webDirAbs)}`;
  }

  return checkOhosConfigFiles(config);
}

async function checkOhosConfigFiles(config: Config): Promise<string | null> {
  const ohPackageJsonPath = join(config.ohos.platformDirAbs, 'oh-package.json5');
  if (!(await pathExists(ohPackageJsonPath))) {
    return `${c.strong('oh-package.json5')} file is missing in ${c.strong(config.ohos.platformDir)}`;
  }

  const buildProfilePath = join(config.ohos.platformDirAbs, 'build-profile.json5');
  if (!(await pathExists(buildProfilePath))) {
    return `${c.strong('build-profile.json5')} file is missing in ${c.strong(config.ohos.platformDir)}`;
  }

  return null;
}